package com.fengplus.demo.service;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

@Service
@DefaultProperties(defaultFallback = "infoGlobalHandler")
public class HystrixService {

    public String infoOk() {
        return Thread.currentThread().getName() + "_OK";
    }

    // 逻辑错误
    @HystrixCommand(fallbackMethod = "infoErrorHandler")
    public String infoError() {
        int i = 10 / 0;
        return Thread.currentThread().getName() + "_Error";
    }

    public String infoErrorHandler(){
        return Thread.currentThread().getName() + "_ErrorHandler";
    }

    // 超时
    @HystrixCommand(fallbackMethod = "infoTimeoutHandler", commandProperties = {
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500")
    })
    public String infoTimeout() {
        try {
            Thread.sleep(800);
        }catch (Exception e){
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "_TimeOut";
    }

    public String infoTimeoutHandler(){
        return Thread.currentThread().getName() + "_TimeoutHandler";
    }

    // 全局参数
    @HystrixCommand
    public String infoGlobal() {
        int i = 10 / 0;
        return Thread.currentThread().getName() + "_Global";
    }

    public String infoGlobalHandler(){
        return Thread.currentThread().getName() + "_GlobalHandler";
    }

    // 消费者调用，降级方法在消费端
    public String infoFeign() {
        int i = 10 / 0;
        return Thread.currentThread().getName() + "_FeignError";
    }

    // 熔断
    // 测试方法：
    // 1、访问错误地址6次，触发熔断，http://127.0.0.1:8203/hystrix/breaker/-1
    // 2、访问正确地址，看到错误，http://127.0.0.1:8203/hystrix/breaker/1
    // 3、继续访问正确地址，看到熔断恢复
    @HystrixCommand(fallbackMethod = "infoBreakerHandler", commandProperties = {
        @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 是否开启断路器
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间范围,10秒
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60") // 失败率达到后跳闸
    })
    public String infoBreaker(Long id) {
        if(id < 0){
            throw new RuntimeException("id异常");
        }
        return Thread.currentThread().getName() + "_Breaker";
    }

    public String infoBreakerHandler(Long id){
        return Thread.currentThread().getName() + "_BreakerHandler";
    }

}
